import {apiOption, common} from 'Api'
import {observable} from 'mobx'
import {Role} from 'Model/role'

class rootStore {
  // 登录状态
  @observable
  private _isLogin = true

  private _role?: Role

  get isLogin() {
    return this._isLogin
  }

  set isLogin(value: boolean) {
    this._isLogin = value
  }

  get role() {
    return this._role
  }

  errorHandle(status: number) {
    if (status == 403 && this._isLogin) {
      window.alert('登录已超时，请重新登录')
      this.logout()
    }
  }

  init() {
    const userId = sessionStorage.getItem('userId')
    const roleId = parseInt(sessionStorage.getItem('roleId') || '')
    const token = sessionStorage.getItem('token')
    console.log(userId, roleId, token)
    if (userId && roleId && token) {
      apiOption.setOnError(this.errorHandle)
      apiOption.setCredentials(token, parseInt(userId, 10), roleId)
      this._role = roleId as Role
      this._isLogin = true
    }
  }

  async login(userName: string, password: string) {
    const res = await common.login({
      name: userName,
      password,
    })
    if (res.success && res.data) {
      sessionStorage.setItem('userId', res.data.id)
      sessionStorage.setItem('roleId', res.data.role_id)
      sessionStorage.setItem('token', res.data.token)
      sessionStorage.setItem('username', res.data.username)
      this.init()
    }
    return res
  }

  logout() {
    sessionStorage.removeItem('userId')
    sessionStorage.removeItem('roleId')
    sessionStorage.removeItem('token')
    sessionStorage.removeItem('username')
    this._isLogin = false
  }
}

export default rootStore
